---
import { type KnownLanguageCode } from "../../consts";
import type { CollectionEntry } from "astro:content";
import { SIDEBAR, SIDEBAR_HEADER_MAP } from "../../consts";
import { getIsRtlFromUrl } from "../../languages";
// import Search from "./Search";
import { cn } from "@/lib/utils";

type DataProps = CollectionEntry<"docs">["data"];

export interface Props {
  frontmatter?: DataProps;
  currentPage: string;
  isNotFound?: boolean;
}

const { frontmatter, currentPage, isNotFound } = Astro.props;
const isLanding = currentPage === "/" || !!isNotFound;
const hasTrailing = currentPage.endsWith("/");
const currentPageMatch = currentPage.slice(
  1,
  hasTrailing ? -1 : currentPage.length,
);
const isRtl = getIsRtlFromUrl(currentPage);

const langCode = frontmatter?.lang ?? "en";
const englishSidebar = SIDEBAR["en"];
const nativeSidebar = SIDEBAR[langCode as keyof typeof SIDEBAR]; // Use type assertion

let sidebar: Record<
  string,
  { text: string; link: string; isTranslated?: boolean }[]
> = englishSidebar;

if (langCode && langCode !== "en") {
  // Check if langCode is defined
  sidebar = Object.fromEntries(
    Object.entries(englishSidebar).map(([header, items]) => {
      // Set header to translated one if it exists
      const innerHeader = SIDEBAR_HEADER_MAP[langCode as KnownLanguageCode];
      const nativeHeader =
        innerHeader?.[header as keyof typeof innerHeader] ?? header;

      const langCodeLength = langCode.length;
      const nativeItems = items.map((item) => {
        const match = Object.values(nativeSidebar)
          .flat()
          .find(
            ({ link: nativeLink }) =>
              // trailing slash + language code
              nativeLink.slice(langCodeLength + 1) === item.link.slice(3),
          );
        return {
          text: match?.text ?? item.text,
          link: match?.link ?? item.link,
          isTranslated: !!match,
        };
      });

      return [nativeHeader, nativeItems];
    }),
  );
}
---

<div class="w-full">
  {
    Object.entries(sidebar).map(([header, children]) => (
      <div class={cn("pb-4")}>
        <h4 class="mb-1 rounded-md px-2 py-1 text-sm font-semibold">
          {header}
        </h4>
        <div class="grid grid-flow-row auto-rows-max text-sm">
          {children.map((child) => {
            const url = Astro.site?.pathname + child.link;
            const isActive = currentPageMatch === child.link;
            return (
              <a
                href={url}
                aria-current={isActive ? "page" : false}
                class:list={[
                  "group flex w-full items-center rounded-md border border-transparent px-2 py-1 hover:underline",
                  isActive
                    ? "font-medium text-foreground"
                    : "text-muted-foreground",
                  isRtl ? "border-r-2" : "border-l-2",
                ]}
              >
                <span>{child.text}</span>
                {!child.isTranslated && langCode !== "en" && (
                  <span class="text-xs text-ces-400 [margin-inline-start:4px] dark:text-ces-300">
                    EN
                  </span>
                )}
              </a>
            );
          })}
        </div>
      </div>
    ))
  }
</div>
